//
//  CategoryController.m
//  HelloWorld
//
//  Created by Beomjun Kim on 09. 09. 21.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "CategoryController.h"
#import "ProductController.h"
#import "XmlUtil.h"
#import "XMLParser.h"
#import "TreeNode.h"
#import "CategoryListModel.h"


#define URLSTRING_TAG		999

@implementation CategoryController

@synthesize url;
@synthesize resultList;

-(CategoryController *) initWithTitle: (NSString *) title
							 withUrl: (NSString *) xmlUrl
{
	self = [super init];
	
	self.title = title;
	self.url = xmlUrl;
	
	[self.tabBarItem initWithTitle:self.title image:nil tag:0];
	
	return self;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	return [self.resultList count];
}

- (void) modCell:(UITableViewCell *)aCell withIndex:(int)index
{
	CategoryListModel *category = [self.resultList objectAtIndex:index];
	
	// 이미지가 있을 경우에는 해당 URL로부터 직접 갖고 오고, 없을 경우에는 디폴트 이미지를 보여준다.
	UIImage *img;
	if(category.image1){
		NSURL *url = [NSURL URLWithString:category.image1];
		img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];		
	} else {
		img =  [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png" inDirectory:@"/"]];		
	}
	aCell.image = img;
	
	
	// 이름에 해당하는 UILabel 생성
	CGRect tRect1 = CGRectMake(70.0f, 2.0f, 180.0f, 62.0f);
	UILabel *title1 = [[UILabel alloc] initWithFrame:tRect1];
	title1.tag = URLSTRING_TAG;
	[title1 setText:category.name];
	[title1 setTextAlignment:UITextAlignmentLeft];
	[title1 setFont: [UIFont fontWithName:@"Helvetica" size:18.0f]];
	[title1 setBackgroundColor:[UIColor clearColor]];	
	
	// 개수에 해당하는 UILabel 생성
	CGRect tRect2 = CGRectMake(260.0f, 2.0f, 40.0f, 60.0f);
	UILabel *title2 = [[UILabel alloc] initWithFrame:tRect2];
	[title2 setText:category.cnt];
	[title2 setText:[NSString stringWithFormat:@"(%@)", category.cnt]];
	[title2 setTextAlignment:UITextAlignmentRight];
	[title2 setTextColor:[UIColor redColor]];
	[title2 setFont: [UIFont fontWithName:@"Helvetica" size:18.0f]];
	[title2 setBackgroundColor:[UIColor clearColor]];
	
	// 꺽쇠 해당하는 UILabel 생성
	CGRect rightRect = CGRectMake(300.0f, 2.0f, 20.0f, 60.0f);
	UILabel *rightTitle = [[UILabel alloc] initWithFrame:rightRect];
	[rightTitle setText:@">"];
	[rightTitle setTextAlignment:UITextAlignmentCenter];
	//[rightTitle setTextColor:[UIColor redColor]];
	[rightTitle setFont: [UIFont boldSystemFontOfSize:14.0f]];
	[rightTitle setBackgroundColor:[UIColor clearColor]];

	// 셀에 UILabel을 추가한다
	[aCell addSubview:title1];
	[aCell addSubview:title2];
	[aCell addSubview:rightTitle];	
	
	[title1 release];
	[title2 release];
	[rightTitle release];
}

/*
 *	Delegate 메소드
 *
 *	- 테이블의 Row 수만큼 자동으로 호출이 된다.
 */
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:@"any-cell"];
	
	cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"any-cell"] autorelease];
	/*
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"any-cell"] autorelease];
	} else {
		NSArray *views = cell.subviews;
		for(int i=0; i< [views count]; i++){
			UIView *view = [views objectAtIndex:i];
//			view.tag
			[view removeFromSuperview];
		}
	}
	
	// Index를 넘겨서 해당 값을 커스텀 셀을 구성한다.
	 */
	[self modCell:cell withIndex:[indexPath row]];
	
	return cell;
}

/*
 *  Delegate Methods - This doesn't do anything, plus Apple has removed App launching from the SDK arsenal
 */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath 
{
	CategoryListModel *category = [self.resultList objectAtIndex:newIndexPath.row];
	printf("User selected %s\n",  [category.name UTF8String]);
	
	// 카테고리별 상품
	NSString *requestUrl = [NSString stringWithFormat:@"http://www.haroohana.com/iphone/iphone_totalpdt.php?partinfo=%@", category.index];
	ProductController *bControl1 = [[ProductController alloc] initWithTitle:category.name
																	withUrl:requestUrl];
	[[self navigationController] pushViewController:bControl1 
										   animated:YES];

	[bControl1 release];
}


/*
 * 데이터 소스 설정
 */
-(void) setDataSource
{
	// XML 결과를 가져온다.
	XMLParser *parser = [[XMLParser alloc] init];
	TreeNode *root = [parser parseXMLFile:[NSURL URLWithString:self.url]];
	self.resultList = [[[NSMutableArray alloc] init] autorelease];

	// rss로 한번 감싸여져 있다.
	root = [[root children] objectAtIndex:0];
	
	int size = [[root children] count];	
	
	NSLog(@"Category Size : %d\n",  size);

	for(int i=0; i<size; i++) 
	{
		TreeNode *list = [[root children] objectAtIndex:i];
		
		if([list.key isEqual:@"category"]){
			CategoryListModel *model = [[CategoryListModel alloc] init];
			
			model.index = [XmlUtil stringForPath:@"index" ofNode:list];
			model.name = [XmlUtil stringForPath:@"name" ofNode:list];
			//		model.image1 = [XmlUtil stringForPath:@"image1" ofNode:list];
			//		model.cnt = [XmlUtil stringForPath:@"cnt" ofNode:list];
			model.cnt = @"1";
			
			[self.resultList addObject:model];			
		}
	}

	/*
	 self.categoryArray = [NSArray arrayWithObjects:
	 @"IT/가전", 
	 @"패션", 
	 @"화장품/미용", 
	 @"유아/식품", 
	 @"건강/스포츠",
	 @"가구/인테리어/주방",
	 @"도서/팬시",
	 @"여행",
	 @"해외상품",
	 @"기타",
	 nil];
	 */
}


- (void)loadView
{
	[super loadView];
	[self.tableView setRowHeight:64];
	
	[self setDataSource];
}

@end